package com.md.notes.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.md.notes.R;


import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.md.notes.activity.WriteActivity;
import com.md.notes.adapter.NoteAdapter;
import com.md.notes.model.db.service.DaoService;
import com.md.notes.model.entity.Note;
import com.md.notes.model.module.file.FileMgrModel;

import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
 * A simple {@link Fragment} subclass.
 * Use the {@link NoteFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NoteFragment extends Fragment {
    // 添加新的成员变量
    private ActivityResultLauncher<Intent> noteActivityLauncher;
    private RecyclerView recyclerView;
    private NoteAdapter adapter;
    private Button btnAdd;
    private List<Note> notes = new ArrayList<>();

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private DaoService daoService;

    public NoteFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NoteFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NoteFragment newInstance(String param1, String param2) {
        NoteFragment fragment = new NoteFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        // 注册 ActivityResultLauncher
        noteActivityLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // 当WriteActivity返回时，重新加载数据
                        loadData();
                        Toast.makeText(getContext(), "笔记已更新", Toast.LENGTH_SHORT).show();
                    }
                }
        );

        daoService = new DaoService(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_note, container, false);

        initRecyclerView(view);
        initTitleBar();
        loadData();

        return view;
    }

    @Override
    @MainThread
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {


    }

    private void initRecyclerView(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        btnAdd = view.findViewById(R.id.btnAdd);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new NoteAdapter(notes);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(note -> {
            // 处理点击事件
            Toast.makeText(getContext(), "点击了: " + note.getTitle(), Toast.LENGTH_SHORT).show();
            // 使用 launcher 启动 WriteActivity
            Intent intent = new Intent(getActivity(), WriteActivity.class);
            // 存储枚举的字符串表示
            intent.putExtra("type", WriteActivity.FragmentType.VIEW.name());
            intent.putExtra("content",note.getContent());
            noteActivityLauncher.launch(intent);
        });
    }

    private void initTitleBar() {
        btnAdd.setOnClickListener(v -> {
            Toast.makeText(getContext(), "点击了新建按钮", Toast.LENGTH_SHORT).show();
            // TODO: 实现新建笔记的功能
            // 使用 launcher 启动 WriteActivity
            Intent intent = new Intent(getActivity(), WriteActivity.class);
            // 存储枚举的字符串表示
            intent.putExtra("type", WriteActivity.FragmentType.EDIT.name());
            noteActivityLauncher.launch(intent);
        });
    }

    private void loadData() {
        // 模拟数据
        /*notes.add(new Note("项目计划书", "MD001", "2023-06-15"));
        notes.add(new Note("每周总结报告", "MD002", "2023-06-14"));
        notes.add(new Note("产品需求文档", "MD003", "2023-06-13"));
        notes.add(new Note("会议纪要", "MD004", "2023-06-12"));
        notes.add(new Note("学习笔记", "MD005", "2023-06-11"));*/
        //FileMgrModel fileMgrModel = new FileMgrModel();
        notes.clear();
        //notes.addAll(fileMgrModel.getNoteList());
        notes.addAll(daoService.getAllNotes());
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {

        super.onDestroyView();
    }
}